package com.quanyan.stadium.web.api;

import com.quanyan.api.APIResponse;
import com.quanyan.api.enums.ApiResponseEnum;
import com.quanyan.common.utils.*;
import com.quanyan.stadium.api.req.*;
import com.quanyan.stadium.biz.BizDatesportJoinInfoDao;
import com.quanyan.stadium.entity.TbDatesportInfo;
import com.quanyan.stadium.entity.TbDatesportInfoExample;
import com.quanyan.stadium.entity.TbDatesportJoinInfo;
import com.quanyan.stadium.entity.TbDatesportJoinInfoExample;
import com.quanyan.stadium.entity.vo.MemberInfo;
import com.quanyan.stadium.mapper.DatesportMapper;
import com.quanyan.stadium.mapper.TbDatesportInfoMapper;
import com.quanyan.stadium.mapper.TbDatesportJoinInfoMapper;
import com.quanyan.stadium.service.commonComponent.BaseService;
import com.quanyan.stadium.service.DatesportService;
import com.quanyan.user.response.RespUserInfoBase;
import com.quanyan.user.serviceFacade.UserServiceFacade;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by Zheng.Ke
 * Date 2016/7/7.
 */
@RestController
@RequestMapping("/api/datesport")
public class DatesportController {
    private static Logger logger = LoggerFactory.getLogger(DatesportController.class);
    @Autowired
    private DatesportService datesportService;
    @Autowired
    private TbDatesportInfoMapper tbDatesportInfoMapper;
    @Autowired
    private BizDatesportJoinInfoDao bizDatesportJoinInfoDao;
    @Autowired
    private BaseService baseService;
    @Autowired
    private DatesportMapper datesportMapper;
    @Autowired
    private UserServiceFacade userServiceFacade;
    @Autowired
    private TbDatesportJoinInfoMapper tbDatesportJoinInfoMapper;

    @RequestMapping(value = "/createDatesportNotice", method = RequestMethod.POST)
    public APIResponse<?> createDatesportNotice(@RequestBody @Valid ReqDatesportNotice reqDatesportNotice, BindingResult result) {
        Integer uid = (Integer) ServletUtils.getHttpServletRequest().getAttribute("uid");
        if (uid == null || uid == 0) {
            return APIResponse.returnFail(ApiResponseEnum.NEED_USER_LOGIN);
        }
        if (result.hasErrors()) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID, result.getFieldError().getField() + "" + result.getFieldError().getDefaultMessage());
        }

        return datesportService.createDatesportNotice(reqDatesportNotice, uid);
    }

    @RequestMapping(value = "/createDatesportLabel", method = RequestMethod.POST)
    public APIResponse<?> createDatesportLabel(@RequestBody @Valid ReqDatesportLabelInfo reqDatesportLabelInfo, BindingResult result) {
        Integer uid = (Integer) ServletUtils.getHttpServletRequest().getAttribute("uid");
        if (uid == null || uid == 0) {
            return APIResponse.returnFail(ApiResponseEnum.NEED_USER_LOGIN);
        }
        if (result.hasErrors()) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID, result.getFieldError().getField() + "" + result.getFieldError().getDefaultMessage());
        }
        reqDatesportLabelInfo.setUid(uid);

        return datesportService.createDatesportLabel(reqDatesportLabelInfo);
    }

    @RequestMapping(value = "/createDatesportSet", method = RequestMethod.POST)
    public APIResponse<?> createDatesportSet(@RequestBody @Valid ReqDatesportSetInfo reqDatesportSetInfo, BindingResult result) {
        if (result.hasErrors()) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID, result.getFieldError().getField() + "" + result.getFieldError().getDefaultMessage());
        }

        return datesportService.createDatesportSet(reqDatesportSetInfo);
    }

    /**
     * 约运动详情接口
     * @param reqDatesportDetail
     * @param result
     * @return
     */
    @RequestMapping(value = "/datesportDetail", method = RequestMethod.POST)
    public APIResponse<?> datesportDetail(@RequestBody @Valid ReqDatesportDetail reqDatesportDetail, BindingResult result) {
        if (result.hasErrors()) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID, result.getFieldError().getField() + "" + result.getFieldError().getDefaultMessage());
        }

        return datesportService.datesportDetail(reqDatesportDetail);
    }

    /**
     * 获取约运动推荐人接口
     * @param reqRecommendInfo
     * @param result
     * @return
     */
    @RequestMapping(value = "/recommendInfo", method = RequestMethod.POST)
    public APIResponse<?> recommendInfo(@RequestBody @Valid ReqRecommendInfo reqRecommendInfo, BindingResult result) {
        if (result.hasErrors()) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID, result.getFieldError().getField() + "" + result.getFieldError().getDefaultMessage());
        }
        APIResponse response = datesportService.recommendInfo(reqRecommendInfo);
        logger.info("约运动：推荐人接口。请求{}。晌应：{}。", GsonUtils.toJson(reqRecommendInfo), GsonUtils.toJson(response));
        return response;
    }

    /**
     * 邀请用户接口
     * @param reqInvite
     * @param result
     * @return
     */
   @RequestMapping(value = "/invitePeople", method = RequestMethod.POST)
    public APIResponse<?> invitePeople(@RequestBody @Valid ReqInvite reqInvite, BindingResult result) {
        Integer uid = (Integer) ServletUtils.getHttpServletRequest().getAttribute("uid");
        if (uid == null || uid == 0) {
            return APIResponse.returnFail(ApiResponseEnum.NEED_USER_LOGIN);
        }
        if (result.hasErrors()) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID, result.getFieldError().getField() + "" + result.getFieldError().getDefaultMessage());
        }

        return datesportService.invitePeople(reqInvite.getDatesportId(), reqInvite.getInvitedUid(), uid);
    }

    /**
     * 更新用户的活动状态位
     * @param reqUpdateUserDatesportStatus
     * @param result
     * @return
     */
    @RequestMapping(value = "/updateUserDatesportStatus", method = RequestMethod.POST)
    public APIResponse<?> updateUserDatesportStatus(@RequestBody @Valid ReqUpdateUserDatesportStatus reqUpdateUserDatesportStatus, BindingResult result) {
        if (result.hasErrors()) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID, result.getFieldError().getField() + "" + result.getFieldError().getDefaultMessage());
        }
        APIResponse response = datesportService.updateUserDatesportStatus(reqUpdateUserDatesportStatus);

        logger.info("约运动：更新用户的活动状态位。请求{}。映应{}。", GsonUtils.toJson(reqUpdateUserDatesportStatus), GsonUtils.toJson(response));
        return response;
    }

    /**
     * 搜索约运动列表
     * @param reqQueryDatesport
     * @param result
     * @return
     */
    @RequestMapping(value = "/queryDatesport", method = RequestMethod.POST)
    public APIResponse<?> queryDatesport(@RequestBody @Valid ReqQueryDatesport reqQueryDatesport, BindingResult result) {
        Integer uid = (Integer) ServletUtils.getHttpServletRequest().getAttribute("uid");
        if (result.hasErrors()) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID, result.getFieldError().getField() + "" + result.getFieldError().getDefaultMessage());
        }

        return datesportService.queryDatesport(reqQueryDatesport, uid);
    }

    /**
     * 查找用户所参加的约运动列表
     * @param reqQueryMyDatesport
     * @param result
     * @return
     */
    @RequestMapping(value = "/queryMyDatesport", method = RequestMethod.POST)
    public APIResponse<?> queryMyDatesport(@RequestBody @Valid ReqQueryMyDatesport reqQueryMyDatesport, BindingResult result) {
        Integer uid = (Integer) ServletUtils.getHttpServletRequest().getAttribute("uid");
        if (uid == null || uid == 0) {
            return APIResponse.returnFail(ApiResponseEnum.NEED_USER_LOGIN);
        }
        if (result.hasErrors()) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID, result.getFieldError().getField() + "" + result.getFieldError().getDefaultMessage());
        }

        return datesportService.queryMyDatesport(uid, reqQueryMyDatesport.getPageNum(), reqQueryMyDatesport.getPageSize());
    }

    /**
     * 获取已参加约运动的成员列表
     * @param reqGetJoinedList
     * @param result
     * @return
     */
    @RequestMapping(value = "/getJoinedList", method = RequestMethod.POST)
    public APIResponse<?> getJoinedList(@RequestBody @Valid ReqGetJoinedList reqGetJoinedList, BindingResult result) {
        if (result.hasErrors()) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID, result.getFieldError().getField() + "" + result.getFieldError().getDefaultMessage());
        }
        int datesportId = reqGetJoinedList.getDatesportId();

        return datesportService.getJoinedList(datesportId, reqGetJoinedList.getPageNum(), reqGetJoinedList.getPageSize());
    }

    /**
     * 取消约运动
     * @param reqCancelDatesport
     * @param result
     * @return
     */
    @RequestMapping(value = "/cancelDatesport", method = RequestMethod.POST)
    public APIResponse<?> cancelDatesport(@RequestBody @Valid ReqCancelDatesport reqCancelDatesport, BindingResult result) {
        Integer uid = (Integer) ServletUtils.getHttpServletRequest().getAttribute("uid");
        if (uid == null || uid == 0) {
            return APIResponse.returnFail(ApiResponseEnum.NEED_USER_LOGIN);
        }
        if (result.hasErrors()) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID, result.getFieldError().getField() + "" + result.getFieldError().getDefaultMessage());
        }
        int datesportId = reqCancelDatesport.getDatesportId();

        return datesportService.cancelDatesport(datesportId, uid);
    }

    /**
     * 优化表结构时，初始化（只需调用一次）
     * @return
     */
    @RequestMapping(value = "/init2", method = RequestMethod.POST)
    public APIResponse<?> init2() {
        logger.info("初始化start...");
        TbDatesportJoinInfoExample example = new TbDatesportJoinInfoExample();
        List<TbDatesportJoinInfo> joinInfoList = tbDatesportJoinInfoMapper.selectByExample(example);
        List<Integer> uids = new ArrayList<>();
        for (TbDatesportJoinInfo joinInfo : joinInfoList) {
            uids.add(joinInfo.getUid());
        }

        Map<Integer, RespUserInfoBase> map = userServiceFacade.batchQueryUserInfoToMap(uids);
        if (map != null) {
            for (TbDatesportJoinInfo joinInfo : joinInfoList) {
                if (map.containsKey(joinInfo.getUid())) {
                    RespUserInfoBase userInfoBase = map.get(joinInfo.getUid());
                    joinInfo.setGender((byte) userInfoBase.getGender().intValue());
                    tbDatesportJoinInfoMapper.updateByPrimaryKeySelective(joinInfo);
                }
            }
        }

        TbDatesportInfoExample example2 = new TbDatesportInfoExample();
        TbDatesportInfoExample.Criteria criteria = example2.createCriteria();
        criteria.andGroupIdIsNotNull();
        criteria.andGenderStructureEqualTo((byte) 0);

        List<TbDatesportInfo> infoList = tbDatesportInfoMapper.selectByExample(example2);
        for (TbDatesportInfo info : infoList) {
            if (StringUtil.isBlankOrNull(info.getGroupId())) {
                continue;
            }
            // 参与人性别结构
            Byte gender = bizDatesportJoinInfoDao.getMaxJoinedPeopleGender(info.getId(), null, true);
            info.setGenderStructure(gender);

            tbDatesportInfoMapper.updateByPrimaryKeySelective(info);
        }
        logger.info("初始化end...");
        return APIResponse.returnSuccess("OK");
    }

    /**
     * 优化表结构时，初始化（只需调用一次）
     * @return
     */
    @RequestMapping(value = "/init", method = RequestMethod.POST)
    public APIResponse<?> init() {
        logger.info("初始化start...");
        TbDatesportInfoExample example = new TbDatesportInfoExample();
        TbDatesportInfoExample.Criteria criteria = example.createCriteria();
        criteria.andGroupIdIsNotNull();
        criteria.andJoinedCountIsNull();

        List<TbDatesportInfo> infoList = tbDatesportInfoMapper.selectByExample(example);
        for (TbDatesportInfo info : infoList) {
            if (StringUtil.isBlankOrNull(info.getGroupId())) {
                continue;
            }
            List<TbDatesportJoinInfo> joinInfoList = bizDatesportJoinInfoDao.findJoinedByDatesportId(info.getId());
            info.setJoinedCount(joinInfoList.size());

            List<MemberInfo> memberInfoList = new ArrayList<>();
            for (TbDatesportJoinInfo joinInfo : joinInfoList) {
                RespUserInfoBase joinUserInfo = baseService.queryUserMsg(joinInfo.getUid());
                if (joinUserInfo == null || joinInfo.getUid() == null) {
                    continue;
                }
                MemberInfo memberInfo = new MemberInfo();
                memberInfo.setUid(joinUserInfo.getUid());
                memberInfo.setIcon(joinUserInfo.getIcon());
                memberInfo.setNickName(joinUserInfo.getNickName());

                if (joinInfo.getStatus().equals(6)) {
                    if (memberInfoList.size() > 0) {
                        memberInfoList.set(0, memberInfo);
                    } else {
                        memberInfoList.add(memberInfo);
                    }
                } else {
                    memberInfoList.add(memberInfo);
                }
            }

            info.setMembersInfo(GsonUtils.toJson(memberInfoList));

            tbDatesportInfoMapper.updateByPrimaryKeySelective(info);
        }
        logger.info("初始化end...");
        return APIResponse.returnSuccess("OK");
    }



}
